package com.example.myapplication1.util;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OkHttpClientUtils {

    private OkHttpClient client;

    public OkHttpClientUtils() {
        this.client = new OkHttpClient();
    }

    public String get(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                return "Request failed with code: " + response.code();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "Request failed with exception: " + e.getMessage();
        }
    }

    public Map<String, Object> parseResponseToMap(String response) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            jsonObject.keys().forEachRemaining(key -> {
                try {
                    resultMap.put(key, jsonObject.get(key));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    public static void main(String[] args) {
        OkHttpClientUtils httpClient = new OkHttpClientUtils();
        String url = "http://admin.mi9688.top/api1/user/get-baby-choose";
        String response = httpClient.get(url);
        System.out.println(response);
    }
}
